#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/stat.h>

#include "log.hpp"


using namespace std;

//const size_t size = 4097;
//共享内存的大小一般是4096的整数倍
//4097,实际上是操作系统给你的是4096*2的大小,但是我们只能只能使用4097
#define size 4096
const string pathanme = "/home/hanbo";
const int proj_id = 0x6666;
Log log;

key_t GetKey()
{
    key_t k = ftok(pathanme.c_str(),proj_id);
    if (k < 0)
    {
        log(Fatal,"ftok error: %s",strerror(errno));
        exit(1);
    }
    log(Info,"ftok sucess,key is : 0x%x",k);

    return k;
}

int GetShareMemHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k,size,flag);

    if (shmid < 0)
    {
        log(Fatal,"create share memory error: %s",strerror(errno));
        exit(2);
    }

    log(Info,"create share memory success,shmid: %d",shmid);

    return shmid;
}

//创建一个共享内存
int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}

//获取一个共享内存
int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}

// int CreateShm()
// {

// }

#define FIFO_FILE "./myfifo"
#define MODE 0664

enum{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
         //创建信道
        int n = mkfifo(FIFO_FILE,MODE);

        if (n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }

    ~Init()
    {
        int m = unlink(FIFO_FILE);

        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};



#endif
